<template>
  <div>
    <el-row>
      <el-button type="primary" @click="addPoint">添加节点</el-button>
    </el-row>
    <el-row
      ><div id="map" ref="mapElement" style="width: 100%; height: 93vh"></div
    ></el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import XYZ from "ol/source/XYZ";
import Map from "ol/Map";
import View from "ol/View";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import Icon from "ol/style/Icon";
import Style from "ol/style/Style";
import "ol/ol.css";

const mapElement = ref(null);
const map = ref(null);
const vectorSource = ref(new VectorSource());

const addPoint = () => {
  const markIcon = require("@/assets/icons/markicon.png");
  // 创建点（元素一律都是 Feature）
  const feature = new Feature({
    geometry: new Point([121.4, 31.4]),
    data: {
      name: "测试点",
      status: "严重",
    },
  });
  // 创建样式
  const style = new Style({
    image: new Icon({
      src: markIcon,
      anchor: [0.5, 0.5],
    }),
  });
  feature.setStyle(style);
  // 添加到图层中
  vectorSource.value.addFeature(feature);
};

onMounted(() => {
  map.value = new Map({
    target: mapElement.value,
    layers: [
      new TileLayer({
        title: "高德地图",
        source: new XYZ({
          url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
          // url: "http://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
          wrapX: false,
        }),
      }),
      // 添加一个图层专门用于显示节点
      new VectorLayer({
        source: vectorSource.value,
      }),
    ],
    view: new View({
      // 中心点位定到宝山附近
      center: [121.4, 31.4],
      zoom: 12, // 地图缩放级别
      projection: "EPSG:4326", // 地图投影
    }),
    // view: new View({
    //   center: [1164074.074, 4328150.506], // 地图中心点
    //   zoom: 7, // 地图缩放级别，可以根据需要调整
    //   projection: "EPSG:3857", // 地图投影
    // }),
  });

  // 添加点击事件
  map.value.on("click", (event) => {
    const feature = map.value.forEachFeatureAtPixel(event.pixel, (feature) => {
      return feature;
    });
    if (feature) {
      let data = feature.get("data");
      alert(data.name);
    }
  });
});
</script>

<style>
/* #app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
} */
</style>
